package me.zhengjie.modules.workorder.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.workorder.domain.TTasks;
import me.zhengjie.modules.workorder.service.TTasksService;
import me.zhengjie.modules.workorder.service.dto.TTasksQueryCriteria;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.HttpResponseUtils;
import me.zhengjie.utils.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author zcw
* @date 2019-08-10
*/
@RestController
@RequestMapping("api")
public class TTasksController {

    @Autowired
    private TTasksService tTasksService;

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Log("查询TTasks")
    @GetMapping(value = "/tTasks")
    //@PreAuthorize("hasAnyRole('ADMIN','TTASKS_ALL','TTASKS_SELECT')")
    public ResponseEntity getTTaskss(TTasksQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(tTasksService.queryAll(criteria,pageable),HttpStatus.OK);
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @GetMapping(value = "/tTasks/order")
    //@PreAuthorize("hasAnyRole('ADMIN','TTASKS_ALL','TTASKS_SELECT')")
    public ResponseEntity getTTaskssWithOrder(TTasksQueryCriteria criteria){
        return new ResponseEntity(tTasksService.queryAll(criteria),HttpStatus.OK);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Log("新增TTasks")
    @PostMapping(value = "/tTasks")
    //@PreAuthorize("hasAnyRole('ADMIN','TTASKS_ALL','TTASKS_CREATE')")
    public ResponseEntity create(@Validated @RequestBody TTasks resources){
        return new ResponseEntity(tTasksService.create(resources),HttpStatus.CREATED);
    }

    @SuppressWarnings("rawtypes")
	@Log("修改TTasks")
    @PutMapping(value = "/tTasks")
    //@PreAuthorize("hasAnyRole('ADMIN','TTASKS_ALL','TTASKS_EDIT')")
    public ResponseEntity update(@Validated @RequestBody TTasks resources){
        tTasksService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @SuppressWarnings("rawtypes")
	@Log("删除TTasks")
    @DeleteMapping(value = "/tTasks/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','TTASKS_ALL','TTASKS_DELETE')")
    public ResponseEntity delete(@PathVariable Long id){
        tTasksService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Log("批量新增TTasks")
    @PostMapping(value = "/tTasks/batch")
    //@PreAuthorize("hasAnyRole('ADMIN','TTASKS_ALL','TTASKS_CREATE')")
    public ResponseEntity upload(@RequestParam String startTime,
                                 @RequestParam Long customerId,
                                 @RequestParam String customerName,
                                 @RequestParam String taskTitle,
                                 @RequestParam String taskContent,
                                 @RequestParam("file") MultipartFile file){
        InputStream inputStream = null;
        Workbook workbook = null;
        try{
            inputStream = file.getInputStream();
            String xlsx = "xlsx";
            String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
            if(suffix.equals(xlsx)) {
                workbook = new XSSFWorkbook(inputStream);
            }else{
                workbook = new HSSFWorkbook(inputStream);
            }
            Sheet sheet = workbook.getSheetAt(0);

            int rowNo = 0;
            int flag = 2;
            List<TTasks> tasksList = new ArrayList<TTasks>();
            for(Row row: sheet) {
                rowNo++;
                if(rowNo >= 3) { //第三行开始有数据
                    String province = getCellStringValue(row.getCell(0), xlsx);
                    String city = getCellStringValue(row.getCell(1), xlsx);
                    String taskAddr = getCellStringValue(row.getCell(2), xlsx);
                    String linker = getCellStringValue(row.getCell(3), xlsx);
                    String cellphone = getCellStringValue(row.getCell(4), xlsx);
                    String date1 = getCellStringValue(row.getCell(5), xlsx);
                    String time1 = getCellStringValue(row.getCell(6), xlsx);
                    String date2 = getCellStringValue(row.getCell(7), xlsx);
                    String time2 = getCellStringValue(row.getCell(8), xlsx);
                    String notes = getCellStringValue(row.getCell(9), xlsx);

                    if(StringUtils.isEmpty(province) && StringUtils.isEmpty(city) && StringUtils.isEmpty(taskAddr) && StringUtils.isEmpty(linker)
                            && StringUtils.isEmpty(cellphone) && StringUtils.isEmpty(date1) && StringUtils.isEmpty(time1) && StringUtils.isEmpty(date2)
                            && StringUtils.isEmpty(time2) && StringUtils.isEmpty(notes)) {
                        continue;
                    } else if(StringUtils.isEmpty(province) || StringUtils.isEmpty(city) ||
                                StringUtils.isEmpty(taskAddr) ||
                                StringUtils.isEmpty(linker) || StringUtils.isEmpty(cellphone) ||
                                StringUtils.isEmpty(date1) || StringUtils.isEmpty(time1) ||
                                StringUtils.isEmpty(date2) ||StringUtils.isEmpty(time2)) {
                        return HttpResponseUtils.passDefaultResponse(String.format("第%d行存在空值",rowNo),HttpStatus.BAD_REQUEST);
                        //TODO@@@@@ 具体列判断
                    }

                    TTasks tTasks = new TTasks();
                    tTasks.setTaskAddr(taskAddr);
                    tTasks.setLinker(linker);
                    tTasks.setCellphone(cellphone);
                    tTasks.setNotes(notes);

                    String d1 = DateUtil.parseDateToStr(new Date(date1),DateUtil.DATE_FORMAT_YYYY_MM_DD);
                    String t1 = DateUtil.parseDateToStr(new Date(time1),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                    tTasks.setArriveTime(new Timestamp(DateUtil.parseStrToDate(String.format("%s %s",d1,t1.substring(11)),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI).getTime()));

                    String d2 = DateUtil.parseDateToStr(new Date(date2),DateUtil.DATE_FORMAT_YYYY_MM_DD);
                    String t2 = DateUtil.parseDateToStr(new Date(time2),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                    tTasks.setFinishTime(new Timestamp(DateUtil.parseStrToDate(String.format("%s %s",d2,t2.substring(11)),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI).getTime()));
                    tTasks.setStartTime(new Timestamp(DateUtil.parseStrToDate(startTime,DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS).getTime()));
                    tTasks.setCustomerId(customerId);
                    tTasks.setCustomerName(customerName);
                    tTasks.setCountry("中国");
                    tTasks.setProvince(province);
                    tTasks.setCity(city);
                    tTasks.setCounty("");
                    tTasks.setTaskTitle(taskTitle);
                    tTasks.setTaskContent(taskContent);
                    tTasks.setAttachments("");
                    tasksList.add(tTasks);
                }
            }
            if(tasksList.size() >= 1) {
                tTasksService.create(tasksList);
            }
            return new ResponseEntity(HttpStatus.OK);
        }catch(Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }


     private String getCellStringValue(Object obj, String xlsx) {
         if (obj == null)
             return "";
         Cell cell = null;
         if (xlsx.equals("xlsx")) {
             cell = (XSSFCell) obj;
         } else {
             cell = (HSSFCell) obj;
         }
         switch (cell.getCellTypeEnum()) {
             case FORMULA:
                 return cell.getCellFormula();
             case NUMERIC:
                 if(org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)){
                     Date date = cell.getDateCellValue();
                     return date.toString();
                 }else {
                     DecimalFormat decimalFormat = new DecimalFormat("#");
                     return decimalFormat.format(cell.getNumericCellValue());
                 }
             default:
                 return cell.getStringCellValue();
         }
     }
}